<template>
  <div>
    <h3>个人信息</h3>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="110px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="学员姓名" prop="realName">
            <el-input v-model="ruleForm.realName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="ruleForm.idNumber" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="ruleForm.mobile" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="ruleForm.gender" placeholder="">
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="家庭地址" prop="location">
            <el-input v-model="ruleForm.location" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证照片" prop="name">
            <el-row :gutter="12">
              <el-col :span="12">
                <el-input v-model="ruleForm.cardFrontImg" style="display: none"></el-input>
                <div class="avatar-uploader" @click="openImageDialog('cardFrontImg')">
                  <el-image v-if="cardFrontImg" :src="cardFrontImg" class="avatar" fit="contain"></el-image>
                  <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                      <Plus />
                    </el-icon></i>
                  <div v-if="cardFrontImg" class="mask">替换</div>
                  <el-icon v-if="cardFrontImg" class="del-image" :size="20" @click.stop="handleDelImg('cardFrontImg')">
                    <CircleCloseFilled />
                  </el-icon>
                </div>
                <div style="text-align: center">身份证正面</div>
              </el-col>
              <el-col :span="12">
                <el-input v-model="ruleForm.cardBackImg" style="display: none"></el-input>
                <div class="avatar-uploader" @click="openImageDialog('cardBackImg')">
                  <el-image v-if="cardBackImg" :src="cardBackImg" class="avatar" fit="contain"></el-image>
                  <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                      <Plus />
                    </el-icon></i>
                  <div v-if="cardBackImg" class="mask">替换</div>
                  <el-icon v-if="cardBackImg" class="del-image" :size="20" @click.stop="handleDelImg('cardBackImg')">
                    <CircleCloseFilled />
                  </el-icon>
                </div>
                <div style="text-align: center">身份证反面</div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <div>
    <h3>报名信息</h3>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="110px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="报名时间" prop="applyTime">
            <el-date-picker v-model="ruleForm.applyTime" type="date" placeholder="" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="招生人" prop="recruitingSpecialistId">
            <el-select v-model="ruleForm.recruitingSpecialistId" placeholder="">
              <el-option v-for="(item, index) in props.enrollList" :key="index" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="报名点" prop="registrationSiteId">
            <el-select v-model="ruleForm.registrationSiteId" placeholder="">
              <el-option v-for="(item, index) in props.signList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="教练员" prop="coachId">
            <el-select v-model="ruleForm.coachId" placeholder="">
              <el-option v-for="(item, index) in props.coachList" :key="index" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="报考车型" prop="carModelId">
            <el-select v-model="ruleForm.carModelId" placeholder="">
              <el-option v-for="(item, index) in props.cardsList" :key="index" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="报名班型" prop="storePackageId">
            <el-select v-model="ruleForm.storePackageId" placeholder="">
              <el-option v-for="(item, index) in props.classList" :key="index" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="缴费方式" prop="payType">
            <el-select v-model="ruleForm.payType" placeholder="">
              <el-option label="微信" value="2" />
              <el-option label="支付宝" value="1" />
              <el-option label="现金" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实付金额" prop="realPaySum">
            <el-input v-model="ruleForm.realPaySum">
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <h3>考试状态</h3>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="110px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="当前考试科目" prop="nowExam">
                <el-select v-model="ruleForm.nowExam" placeholder="">
                  <el-option label="科目一" value="1" />
                  <el-option label="科目二" value="2" />
                  <el-option label="科目三" value="3" />
                  <el-option label="科目四" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="报名状态" prop="applyState">
                <el-select v-model="ruleForm.applyState" placeholder="">
                  <el-option label="未报名" value="0" />
                  <el-option label="已报名" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="考试时间" prop="nowExamTime">
                <el-date-picker v-model="ruleForm.nowExamTime" type="date" placeholder="" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="已通过科目" prop="noExam">
                <el-select v-model="ruleForm.noExam" placeholder="" multiple>
                  <el-option label="科目一" value="1" />
                  <el-option label="科目二" value="2" />
                  <el-option label="科目三" value="3" />
                  <el-option label="科目四" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" type="textarea" :rows="3" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <div class="btn">
    <el-button type="primary" style="margin-left: 10px" @click="handleSubmit(ruleFormRef)">提交</el-button>
    <el-button @click="emit('close')">取消</el-button>
  </div>
  <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
    :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
    :operationType="false"></image-selected-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { ElMessage, formContextKey } from 'element-plus'
import { AddUsers, EditUsers } from '@/api/userStudentsApi'
import { useUserStore } from '@/store/modules/user'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const userStore = useUserStore()
let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const headers = { Authorization: 'Bearer ' + accessToken }

const emit = defineEmits(['close'])
interface RuleForm {
  realName: string
  idNumber: string
  gender: string
  mobile: string
  location: string
  applyTime: any
  registrationSiteId: string
  recruitingSpecialistId: string
  carModelId: string
  remark: string
  nowExam: string
  realPaySum: string
  noExam: Array<string>
  payType: string
  memberGroupId: string
  storePackageId: string
  cardFrontImg: string
  cardBackImg: string
  id: number
  nowExamTime: string
  applyState: string
  memberId: number
  payState: number
  coachId: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  realName: '',
  idNumber: '',
  gender: '1',
  mobile: '',
  location: '',
  applyTime: new Date(),
  registrationSiteId: '',
  recruitingSpecialistId: '',
  nowExam: '',
  realPaySum: '',
  carModelId: '1',
  noExam: [],
  remark: '',
  payType: '',
  memberGroupId: '',
  storePackageId: '',
  cardFrontImg: '',
  cardBackImg: '',
  id: 0,
  nowExamTime: '',
  applyState: '',
  memberId: 0,
  payState: 0,
  coachId: ''
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) {
    if (currentImageType.value === 'cardFrontImg') {
      cardFrontImg.value = value.fileUrl
    } else {
      cardBackImg.value = value.fileUrl
    }
  }
  showImageChooseDialog.value = false
}

const currentImageType = ref('cardFrontImg')
const openImageDialog = (type: string) => {
  currentImageType.value = type
  showImageChooseDialog.value = true
}

const handleDelImg = (e: string) => {
  if (e === 'cardFrontImg') {
    cardFrontImg.value = ''
  } else {
    cardBackImg.value = ''
  }
}

const rules = reactive<FormRules<RuleForm>>({
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    { min: 11, max: 11, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  idNumber: [
    {
      required: true,
      message: '请输入身份证号',
      trigger: 'blur'
    },
    { min: 18, max: 18, pattern: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '请输入正确的身份证号格式', trigger: 'blur' }
  ],
  payType: [
    { required: true, message: '请选择缴费方式', trigger: 'change' }
  ],
  realPaySum: [
    { required: true, message: '请输入实付金额', trigger: 'blur' }
  ]
})

const handleSubmit = async (formEl: FormInstance | undefined) => {
  console.log(formEl, "formEl==");

  if (!formEl) return
  await formEl.validate(async (valid) => {
    console.log(valid);
    if (!valid) return
    ruleForm.cardFrontImg = cardFrontImg.value
    ruleForm.cardBackImg = cardBackImg.value
    ruleForm.applyTime = ruleForm.applyTime
      ? formatDate(ruleForm.applyTime)
      : '';
    ruleForm.coachId = ruleForm.coachId ? String(ruleForm.coachId) : '';
    ruleForm.nowExamTime = ruleForm.nowExamTime ? formatDate(ruleForm.nowExamTime) : '';
    const submitData = {
      ...ruleForm,
      noExam: Array.isArray(ruleForm.noExam) ? ruleForm.noExam.join(',') : ruleForm.noExam
    }
    let res
    if (props.editList.id) {
      submitData.id = props.editList.id
      submitData.memberId = props.editList.memberId
      const filteredData = filterEmptyValues(submitData)
      res = await EditUsers({
        ...filteredData,
        cardFrontImg: cardFrontImg.value,
        cardBackImg: cardBackImg.value
      })
    } else {
      if ('id' in submitData) {
        delete (submitData as any).id
      }
      if (ruleForm.realPaySum && ruleForm.payType) {
        ruleForm.payState = 1
      } else {
        ruleForm.payState = 0
      }
      submitData.payState = ruleForm.payState
      res = await AddUsers(submitData)
    }
    if (res.code === '00000') {
      ElMessage.success(props.editList.id ? '编辑成功' : '新增成功')
      props.onSuccess && props.onSuccess()
      props.getCardList && props.getCardList()
      emit('close')
    }
  })
}

// 过滤空值的函数
const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
      result[key] = obj[key]
    }
  }
  return result
}

const props = defineProps({
  signList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: () => []
  },
  enrollList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: () => []
  },
  cardsList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: () => []
  },
  classList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: () => []
  },
  userList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: () => []
  },
  coachList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: () => []
  },
  onSuccess: {
    type: Function,
    default: null
  },
  editList: {
    type: Object,
    default: () => { }
  },
  getCardList: {
    type: Function,
    default: null
  }
})

//身份证正面
const cardFrontImg = ref('')
// 身份证反面
const cardBackImg = ref('')
const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
onMounted(() => {
  console.log(props.editList, "props.editList==");
  if (props.editList.id) {
    initializeFromEditList()
  } else {
    resetToCreate()
  }
})

// 重置为新增状态
const resetToCreate = () => {
  cardFrontImg.value = ''
  cardBackImg.value = ''
  ruleForm.applyState = ''
  ruleForm.gender = '1'
  ruleForm.nowExam = ''
  ruleForm.noExam = []
  ruleForm.payType = ''
  ruleForm.realName = ''
  ruleForm.idNumber = ''
  ruleForm.mobile = ''
  ruleForm.location = ''
  ruleForm.applyTime = new Date()
  ruleForm.registrationSiteId = ''
  ruleForm.recruitingSpecialistId = ''
  ruleForm.realPaySum = ''
  ruleForm.carModelId = '1'
  ruleForm.coachId = ''
  ruleForm.remark = ''
  ruleForm.memberGroupId = ''
  ruleForm.storePackageId = ''
  ruleForm.id = 0
  ruleForm.nowExamTime = ''
  ruleForm.memberId = 0
  ruleForm.payState = 0
  ruleFormRef.value?.resetFields()
}

// 从编辑数据初始化
const initializeFromEditList = () => {
  cardFrontImg.value = props.editList.cardFrontImg
  cardBackImg.value = props.editList.cardBackImg
  ruleForm.applyState = props.editList.applyState ? String(props.editList.applyState) : ''
  ruleForm.gender = String(props.editList.gender)
  ruleForm.nowExam = props.editList.nowExam ? String(props.editList.nowExam) : ''
  ruleForm.noExam = props.editList.noExam ? props.editList.noExam.split(',') : []
  ruleForm.payType = props.editList.payType ? String(props.editList.payType) : ''
  ruleForm.realName = props.editList.realName || ''
  ruleForm.idNumber = props.editList.idNumber || ''
  ruleForm.mobile = props.editList.mobile || ''
  ruleForm.location = props.editList.location || ''
  ruleForm.applyTime = props.editList.applyTime
  ruleForm.registrationSiteId = props.editList.registrationSiteId || ''
  ruleForm.recruitingSpecialistId = props.editList.recruitingSpecialistId || ''
  ruleForm.realPaySum = props.editList.realPaySum || ''
  ruleForm.carModelId = props.editList.carModelId || ''
  ruleForm.coachId = props.editList.coachId ? String(props.editList.coachId) : ''
  ruleForm.remark = props.editList.remark || ''
  ruleForm.memberGroupId = props.editList.memberGroupId || ''
  ruleForm.storePackageId = props.editList.storePackageId || ''
  ruleForm.id = props.editList.id || 0
  ruleForm.nowExamTime = props.editList.nowExamTime || ''
  ruleForm.memberId = props.editList.memberId || 0
  ruleForm.payState = props.editList.payState || 0
}

// 监听编辑数据变化，支持编辑后切换为新增时重置
watch(
  () => props.editList && (props.editList as any).id,
  (id) => {
    if (id) {
      initializeFromEditList()
    } else {
      resetToCreate()
    }
  }
)
</script>

<style lang="scss" scoped>
h3 {
  margin-bottom: 20px;
}

.success {
  box-sizing: border-box;
  padding: 15px 100px !important;
  text-align: center;

  .icon {
    display: block;
    margin-top: 6vh;
    font-size: 80px;
    color: #19be6b !important;
  }

  .title {
    margin-top: 20px;
    font-size: 30px;
    font-weight: 500;
    color: var(--art-text-gray-900) !important;
  }

  .msg {
    margin-top: 20px;
    font-size: 16px;
    color: #808695;
  }

  .res {
    padding: 22px 30px;
    margin-top: 30px;
    text-align: left;
    background-color: #f8f8f9;
    border-radius: 5px;

    p {
      padding: 8px 0;
      font-size: 15px;
      color: #808695;
    }
  }

  .btn-group {
    margin-top: 50px;
  }
}

.dark {
  .success {
    .res {
      background: #28282a;
    }
  }
}

.btn {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>
